<?php

namespace app\admin\controller\yiliao;

use app\common\controller\Backend;
use think\Db;
use app\admin\model\yiliao\Doctor;
use app\admin\model\yiliao\Shop;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Pblist extends Backend
{

    /**
     * Pblist模型对象
     * @var \app\admin\model\yiliao\Pblist
     */
    protected $model = null;
	protected $relationSearch = true;
	protected $noNeedRight = ['getShop'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\yiliao\Pblist;
        $this->view->assign("weekdataList", $this->model->getWeekdataList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
	public function getShop()
	{
		$doctorid = $this->request->param('doctorid');
		$row = Doctor::where(['id'=>$doctorid])->find();
		$rows = Shop::where(['id'=>['in',$row['yiliao_shop_ids']]])->select();
		$ret=[];
		foreach($rows as $v){
			$temp=[];
			$temp["id"]=$v['id'];
			$temp["name"]=$v['name'];
			$ret[]=$temp;
		}
		echo json_encode(["list"=>$ret,"total"=>sizeof($ret)]);
	}
	public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
			$ids = $this->request->param('ids');
			$this->assignconfig(["shoping"=>['ids'=>$ids]]);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
		$doctorid = $this->request->param('doctorid');
        $list = $this->model
			->with(['doctor','shop'])
			->where(['yiliao_doctor_id'=>$doctorid])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
	
	public function add()
    {
        if (false === $this->request->isPost()) {
			$doctorid = $this->request->param('doctorid');
			$this->assign("doctorid", $doctorid);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $params['yiliao_pbtimecate_id'] = 1;
		$doctorid = $this->request->param('doctorid');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
		$params['yiliao_doctor_id'] = $doctorid;

		$shangpbtimes = Db::name("yiliao_pbtime")->where(['yiliao_pbtimecate_id'=>$params['yiliao_pbtimecate_id'],'status'=>1,'tdata'=>1])->order("weigh desc")->select();
		$xiapbtimes = Db::name("yiliao_pbtime")->where(['yiliao_pbtimecate_id'=>$params['yiliao_pbtimecate_id'],'status'=>1,'tdata'=>2])->order("weigh desc")->select();
		$shang=[];
		if(sizeof($shangpbtimes)>0 && $params['shangnum']>0){
			$avg1=floor($params['shangnum']/sizeof($shangpbtimes));
			$yu1=$params['shangnum']%sizeof($shangpbtimes);
			foreach($shangpbtimes as $k=>$v){
				if($yu1>0){
					$num=$avg1+1;
					$yu1--;
				}else{
					$num=$avg1;
				}
				$shang[]=['start'=>$v['starttime'],'end'=>$v['endtime'],'num'=>$num];
			}
		}
		$xia=[];
		if(sizeof($xiapbtimes)>0 && $params['xianum']>0){
			$avg2=floor($params['xianum']/sizeof($xiapbtimes));
			$yu2=$params['xianum']%sizeof($xiapbtimes);
			foreach($xiapbtimes as $k=>$v){
				if($yu2>0){
					$num=$avg2+1;
					$yu2--;
				}else{
					$num=$avg2;
				}
				$xia[]=['start'=>$v['starttime'],'end'=>$v['endtime'],'num'=>$num];
			}
		}
		$params['shangtimes']=json_encode($shang);
		$params['xiatimes']=json_encode($xia);
		
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $amtimes[] = ['start'=>"09:00",'end'=>'11:30'];
        $params['amtimes']= json_encode($amtimes);
        $pmtimes[] = ['start'=>"14:00",'end'=>'17:30'];
        $params['pmtimes']= json_encode($pmtimes);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

	public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
			$doctor = Doctor::where(['id'=>$row['yiliao_doctor_id']])->find();
			$rows = Shop::where(['id'=>['in',$doctor['yiliao_shop_ids']]])->select();
			$ret = [];
			foreach($rows as $k=>$v){
				$ret[$v['id']]=$v['name'];
			}
            $this->view->assign('ret', $ret);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $params['yiliao_pbtimecate_id'] = 1;
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

		$shangpbtimes = Db::name("yiliao_pbtime")->where(['yiliao_pbtimecate_id'=>$params['yiliao_pbtimecate_id'],'status'=>1,'tdata'=>1])->order("weigh desc")->select();
		$xiapbtimes = Db::name("yiliao_pbtime")->where(['yiliao_pbtimecate_id'=>$params['yiliao_pbtimecate_id'],'status'=>1,'tdata'=>2])->order("weigh desc")->select();
		$shang=[];
		if(sizeof($shangpbtimes)>0 && $params['shangnum']>0){
			$avg1=floor($params['shangnum']/sizeof($shangpbtimes));
			$yu1=$params['shangnum']%sizeof($shangpbtimes);
			foreach($shangpbtimes as $k=>$v){
				if($yu1>0){
					$num=$avg1+1;
					$yu1--;
				}else{
					$num=$avg1;
				}
				$shang[]=['start'=>$v['starttime'],'end'=>$v['endtime'],'num'=>$num];
			}
		}
		$xia=[];
		if(sizeof($xiapbtimes)>0 && $params['xianum']>0){
			$avg2=floor($params['xianum']/sizeof($xiapbtimes));
			$yu2=$params['xianum']%sizeof($xiapbtimes);
			foreach($xiapbtimes as $k=>$v){
				if($yu2>0){
					$num=$avg2+1;
					$yu2--;
				}else{
					$num=$avg2;
				}
				$xia[]=['start'=>$v['starttime'],'end'=>$v['endtime'],'num'=>$num];
			}
		}
		$params['shangtimes']=json_encode($shang);
		$params['xiatimes']=json_encode($xia);

        $amtimes[] = ['start'=>"09:00",'end'=>'11:30'];
        $params['amtimes']= json_encode($amtimes);
        $pmtimes[] = ['start'=>"14:00",'end'=>'17:30'];
        $params['pmtimes']= json_encode($pmtimes);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
